﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace DotaHelp.Helpers
{
    public class Tag
    {
        private TagBuilder tag;
        
        public Tag(string name, object attributes)
        {
            tag = new TagBuilder(name);
            
            foreach (var p in attributes.GetType().GetProperties())
            {
                var propName = p.Name.Replace("_", "-");
                var propValue = (p.GetValue(attributes, new object[0]) ?? "").ToString();

                if (propValue != null)
                {
                    switch (propName.ToLower())
                    {
                        case "innerhtml": tag.InnerHtml = propValue; break;
                        case "attrs": tag.MergeAttributes(new RouteValueDictionary(p.GetValue(attributes, new object[0]))); break;
                        case "style":
                            if (tag.Attributes.ContainsKey("style"))
                            {
                                tag.Attributes["style"] += ";" + propValue;
                            }
                            else
                            {
                                tag.Attributes.Add("style", propValue);
                            }
                            break;
                        case "class": tag.AddCssClass(propValue); break;
                        default: tag.MergeAttribute(propName, propValue, false); break;
                    }
                }
            }           
        }
             

        public MvcHtmlString ToMvcString()
        {
            return new MvcHtmlString(ToString());
        }

        public override string ToString()
        {
            return tag.ToString();
        }
    }
}